import $ from 'jquery';
import 'select2';

/**
 * ui-select2 指令
 * 
 * 用法示例:
 * 
 * 1. 基础用法:
 * <select ui-select2 ng-model="selectedValue">
 *   <option value="">请选择</option>
 *   <option value="1">选项1</option>
 *   <option value="2">选项2</option>
 * </select>
 * 
 * 2. 配置选项:
 * <select ui-select2="{placeholder: '请选择...', allowClear: true}" ng-model="selectedValue">
 *   <option value="">请选择</option>
 *   <option value="1">选项1</option>
 * </select>
 * 
 * 3. 动态数据:
 * <select ui-select2 ui-select2-data="options" ng-model="selectedValue"></select>
 * 
 * Controller:
 * $scope.options = [
 *   {id: 1, text: '选项1'},
 *   {id: 2, text: '选项2'}
 * ];
 * 
 * 4. 多选:
 * <select ui-select2="{multiple: true}" ng-model="selectedValues" multiple>
 *   <option value="1">选项1</option>
 *   <option value="2">选项2</option>
 * </select>
 */

const uiSelect2Directive = () => {
  'ngInject';
  
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, element, attrs, ngModel) {
      let options = {};
      
      // 解析配置选项
      if (attrs.uiSelect2) {
        options = scope.$eval(attrs.uiSelect2);
      }
      
      // 默认配置
      const defaultOptions = {
        allowClear: true,
        width: '100%',
        theme: 'bootstrap4',
        language: 'zh-CN'
      };
      
      // 合并配置
      options = angular.extend({}, defaultOptions, options);
      
      // 初始化 Select2
      const select2Element = $(element).select2(options);
      
      // 监听 ngModel 变化
      if (ngModel) {
        ngModel.$render = function() {
          $(element).val(ngModel.$viewValue).trigger('change.select2');
        };
        
        // 监听 select2 变化并更新 ngModel
        $(element).on('change.select2', function() {
          scope.$apply(function() {
            ngModel.$setViewValue($(element).val());
          });
        });
        
        // 监听选项变化
        if (attrs.ngOptions) {
          scope.$watch(function() {
            return $(element).find('option').length;
          }, function() {
            $(element).trigger('change.select2');
          });
        }
      }
      
      // 监听配置变化
      if (attrs.uiSelect2) {
        scope.$watch(attrs.uiSelect2, function(newVal, oldVal) {
          if (newVal !== oldVal) {
            $(element).select2('destroy');
            const newOptions = angular.extend({}, defaultOptions, newVal);
            $(element).select2(newOptions);
          }
        }, true);
      }
      
      // 监听数据变化
      if (attrs.uiSelect2Data) {
        scope.$watch(attrs.uiSelect2Data, function(newVal) {
          if (newVal) {
            $(element).empty();
            if (options.allowClear && options.placeholder) {
              $(element).append('<option value=""></option>');
            }
            angular.forEach(newVal, function(item) {
              const value = angular.isObject(item) ? item.id || item.value : item;
              const text = angular.isObject(item) ? item.text || item.name || item.label : item;
              $(element).append('<option value="' + value + '">' + text + '</option>');
            });
            $(element).trigger('change.select2');
          }
        });
      }
      
      // 清理
      scope.$on('$destroy', function() {
        if ($(element).data('select2')) {
          $(element).select2('destroy');
        }
      });
    }
  };
};

// 注册 Select2 中文语言包
if ($ && $.fn.select2) {
  $.fn.select2.amd.define('select2/i18n/zh-cn', [], function() {
    return {
      errorLoading: function() {
        return '无法载入结果。';
      },
      inputTooLong: function(args) {
        var overChars = args.input.length - args.maximum;
        var message = '请删除' + overChars + '个字符';
        return message;
      },
      inputTooShort: function(args) {
        var remainingChars = args.minimum - args.input.length;
        var message = '请再输入' + remainingChars + '个字符';
        return message;
      },
      loadingMore: function() {
        return '载入更多结果…';
      },
      maximumSelected: function(args) {
        var message = '最多只能选择' + args.maximum + '个项目';
        return message;
      },
      noResults: function() {
        return '未找到结果';
      },
      searching: function() {
        return '搜索中…';
      },
      removeAllItems: function() {
        return '删除所有项目';
      }
    };
  });
}

function initUiSelect2Directive() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化ui-select2指令模块');
    return;
  }

  angular.module('app.directives.uiSelect2', [])
    .directive('uiSelect2', uiSelect2Directive);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initUiSelect2Directive();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initUiSelect2Directive();
}